import axios from 'axios'
import type { AxiosInstance } from 'axios'
import * as message from './message'
import { codeEnum } from '@/enums/codeEnum'

const http: AxiosInstance = axios.create({
  baseURL: 'http://43.139.98.171:3000',
  timeout: 5000,
})

const count = 5
let num = 1

// 请求前拦截
http.interceptors.request.use(
  (config) => {
    // const token = JSON.parse(localStorage.getItem('userinfo')).token
    config.headers['Authorization'] = `
    eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJ1c2VyTmFtZSI6IjE4MDY4MzkyMTAiLCJ1c2VySWQiOiIzIn0sImV4cCI6MTY3OTIxMjIzNn0.pcprfuJ101B4cpkQz2ECbQP-Us8DlxE4r-Ok714Q5M8
    `

    return config
  },
  (err) => {
    console.log(err)
  }
)
// 请求数据返回前拦截
http.interceptors.response.use((res) => {
  console.log(res.data, res.config.url)
  message.msg(res.data.code, res.data.msg)
  return res
})

export const get = <T = unknown>(...args: any): Promise<T> => {
  const [url, params] = args
  return new Promise((resolve, reject) => {
    http
      .get(url, { params })
      .then((res) => {
        resolve(res.data)
      })
      .catch(() => {
        if (num <= count) {
          console.log(`重试次数:${num}`)
          num++
          get(url, params)
        } else {
          reject(url + 'get请求失败')
          return
        }
      })
  })
}

export const post = <T = unknown>(...args: any): Promise<T> => {
  const [url, params, headers] = args

  return new Promise((resolve, reject) => {
    http
      .post(url, params, headers)
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject({
          err,
          msg: 'post请求失败',
        })
      })
  })
}

export const del = <T = unknown>(...args: any): Promise<T> => {
  const [url, data, headers] = args
  return new Promise((resolve, reject) => {
    console.log(url)

    http
      .delete(url, {
        data,
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject({
          err,
          msg: 'delete请求失败',
        })
      })
  })
}

export const put = <T = unknown>(...args: any): Promise<T> => {
  const [url, params, headers] = args

  return new Promise((resolve, reject) => {
    console.log(url)
    http
      .put(url, params, headers)
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject({
          err,
          msg: 'put请求失败',
        })
      })
  })
}
